package com.bky.controller;

import com.bky.config.CacheKeyEnum;
import com.bky.config.LoginContext;
import com.bky.model.User;
import com.bky.redis.RedisService;
import com.bky.service.UserService;
import com.bky.util.CookieUtils;
import com.bky.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author shipeilei
 * @Date Created on 2018/5/3
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(User user, HttpServletResponse response){
        if (null == user){
            return "login";
        }
        User u = userService.getUserByName(user.getUserName());
        if (null == u){
            return "login";
        }
        if (u.getUserPwd().equals(user.getUserPwd())){
            CookieUtils.setCookie(response, "sso.jd.com", u.getId().toString(), -1, "");
            redisService.set(u.getId().toString(), JsonUtil.obj2String(u), CacheKeyEnum.KEY_USER.getExp());
            LoginContext.setUser(u);
            return "index";
        }
        return "login";
    }
}
